#include "PatchStomper/StomperModel.h"
#include "PatchStomper/ToolElements/QuadAdder.h"
#include "StompedReality/Core/Input/Keys.h"
#include "StomperLib/RenderHelper.h"
#include <gl\GL.h>
namespace PatchStomper
{
QuadAdder::QuadAdder( StomperLib::BaseLayout* layout, StompedReality::IGame* game,
                      StomperLib::EditorCamera* camera ) : StomperLib::ToolElement( layout, game, camera )
{
  this->m_Visible = false;
  this->m_StartPosition = StompedReality::Math::Vector2( 0, 0 );
  this->m_EndPosition = StompedReality::Math::Vector2( 0, 0 );
}

QuadAdder::~QuadAdder( )
{
}

void QuadAdder::Draw( )
{
  if (!m_Visible)
    return;
  glColor3f( 1, 0, 0 );
  glDisable( GL_TEXTURE_2D );
  StomperLib::RenderHelper::DrawRect( this->m_StartPosition, this->m_EndPosition );
  glEnable ( GL_TEXTURE_2D );
  glColor3f( 1, 1, 1 );
}

bool QuadAdder::Update( )
{
  if (Model->Mode != RectPatchMode )
    return false;
  if (this->GetInputSystem( )->IsLeftButtonDown( ))
  {
    this->m_Visible = true;
    this->m_StartPosition = this->GetMousePos( );
  }

  if (this->GetInputSystem( )->IsKeyDown( KEY_ESCAPE ))
  {
    this->m_Visible = false;
  }

  if (this->m_Visible)
  {
    this->m_EndPosition = this->GetMousePos( );
  }

  if (this->m_Visible && this->GetInputSystem( )->IsLeftButtonUp( ))
  {
    this->m_Visible = false;
    if (this->IsValid( ))
      return ((StomperModel*)Model)->Add( this->GetNormalizedStart( ), this->GetSize( ) );
  }

  return m_Visible;
}

StompedReality::Math::Vector2 QuadAdder::GetNormalizedStart( )
{
  StompedReality::Math::Vector2 res( 0, 0 );
  StompedReality::Math::Vector2 size  = m_EndPosition - m_StartPosition;
  if (size.GetX( ) < 0)
    res.SetX( m_EndPosition.GetX( ));
  else
    res.SetX( m_StartPosition.GetX( ));
  if (size.GetY( ) < 0)
    res.SetY( m_EndPosition.GetY( ));
  else
    res.SetY( m_StartPosition.GetY( ));
  return res;
}

StompedReality::Math::Vector2 QuadAdder::GetSize( )
{
  StompedReality::Math::Vector2 size  = m_EndPosition - m_StartPosition;
  if (size.GetX( ) < 0)
    size.SetX( size.GetX( ) * -1 );
  if (size.GetY( ) < 0)
    size.SetY( size.GetY( ) * -1 );
  return size;
}

bool QuadAdder::IsValid( )
{
  StompedReality::Math::Vector2 size  = m_EndPosition - m_StartPosition;
  return size.Length( ) > 3;
}

}